package cn.com.cetccst.distribution.business.policy;

import android.content.Context;
import android.os.Build;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.BWAppEntity;
import cn.com.cetccst.datacenter.policy.entity.PolicyEntity;
import cn.com.cetccst.datacenter.policy.entity.RestrictionStatusEntity;
import cn.com.cetccst.deviceoperation.DeviceOperator;
import cn.com.cetccst.deviceoperation.OperatorType;
import cn.com.cetccst.distribution.app.AppInfoManager;
import cn.com.cetccst.tools.device.Device;
import cn.com.cetccst.tools.log.CommonLogger;
import cn.com.cetccst.tools.network.Wifi;
import cn.com.cetccst.tools.phone.Phone;
import cn.com.cetccst.tools.pm.AppPackage;

public class PolicyParser {

    public static Result parse(Context context, String cmdName, String content) {
        Result result = new Result();
        if (cmdName.equals(PolicyEntity.POLICY_PASSWORD) ||
                cmdName.equals(PolicyEntity.POLICY_COMPLIANCE) ||
                cmdName.equals(PolicyEntity.POLICY_RESTRICTION) ||
                cmdName.equals(PolicyEntity.POLICY_BLACK_WHITE_SETTING) ||
                cmdName.equals(PolicyEntity.POLICY_VPN_PROFILE) ||
                cmdName.equals(PolicyEntity.POLICY_GENERAL_SETTING) ||
                cmdName.equals(PolicyEntity.POLICY_APP_MANAGEMENT) ||
                cmdName.equals(PolicyEntity.POLICY_WEBSITE_MANAGEMENT) ||
                cmdName.equals(PolicyEntity.POLICY_NETWORK_ACCESS_CONFIG) ||
                cmdName.equals(PolicyEntity.POLICY_APP_SECURITY_CONFIG)) {
            return result;
        } else if (cmdName.equals(PolicyEntity.PARSER_OP_RESTART) ||
                cmdName.equals(PolicyEntity.PARSER_OP_SHUTDOWN) ||
                cmdName.equals(PolicyEntity.PARSER_OP_WIPE_DEVICE) ||
                cmdName.equals(PolicyEntity.PARSER_OP_WIPE_SDCARD) ||
                cmdName.equals(PolicyEntity.PARSER_OP_UNENROLL) ||
                cmdName.equals(PolicyEntity.PARSER_OP_LOCK_DEVICE) ||
                cmdName.equals(PolicyEntity.PARSER_OP_UNLOCK_DEVICE)) {
            DeviceOperator.getInstance().operate(OperatorType.lookUp(cmdName));
//            OperatorManager.getInstance().setCmd(cmdName);
            return result;
        } else if (cmdName.equals(PolicyEntity.POLICY_DEVICE_INFO)){
            result.setMessage(buildDeviceInfo(context));
            return result;
        }

        result.setCode(Result.CODE_ERROR);
        String versionName = AppPackage.getSSVersionName(context);
        String msg = "Un-recognize command, current client VERSION_NAME:" + versionName;
        result.setMessage(msg);
        return result;
    }

    private static String buildDeviceInfo(Context context) {
        Map<String, Object> body = new HashMap<>();

        //---------------------基础信息---------------------------
        body.put("roamingStatus", Phone.isRoaming(context));
        body.put("operator", Phone.getProviderName(context));
        body.put("phoneNumber", Phone.getPhone1Number(context));
        body.put("imei", Device.getDeviceId(context));
        body.put("imsi", Device.getImsi(context));
        body.put("serialNumber", Device.getSerialNumber());
        body.put("wifiMAC", Wifi.getMacAddress(context));
        body.put("dataUsage", null);
        body.put("apiLevel", Build.VERSION.SDK_INT);
        body.put("os", "Android");
        body.put("version", Build.VERSION.RELEASE);
        body.put("manufacturer", Build.MANUFACTURER);
        body.put("brand", Build.BRAND);
        body.put("model", Build.MODEL);
        body.put("deviceName", Device.getDeviceId(context) + "-" + Build.MODEL);
        body.put("jailBroken", Device.isRooted());
        body.put("battery", Device.getBatteryLevel(context) + "%");

        //---------------------存储信息---------------------------
        Map<String, Object> storage = new HashMap<>();
        storage.put("internalTotal", Device.getInternalTotalSize());
        storage.put("internalFree", Device.getInternalAvailableSize());
        storage.put("externalTotal", Device.getExternalTotalSize());
        storage.put("externalFree", Device.getExternalAvailableSize());
        body.put("storage", storage);

        //---------------------应用信息---------------------------
        List<AppInfoManager.AppInfo> infoList = AppInfoManager.getInstance().getInstalledApps(context);
        body.put("appsInfo", infoList);

        //---------------------黑名单应用信息---------------------------
        List<AppInfoManager.AppInfo> blackInfoList = new ArrayList<>();
        List<BWAppEntity> blackApps = PolicyRepository.getInstance().getAllBlackAppEntity();
        for (AppInfoManager.AppInfo info : infoList) {
            for (BWAppEntity entity : blackApps) {
                if (info.getPackageName().equals(entity.getPackageName())) {
                    blackInfoList.add(info);
                }
            }
        }
        body.put("blackAppsInfo", blackInfoList);

        //---------------------设备功能锁信息---------------------------
        Map<String, Object> restriction = new HashMap<>();
        try {
//            IMDMEngine engine = MDMManager.getInstance().getMdmEngine();
//            if (engine == null) {
//                CommonLogger.warn("skip to post DevicePolicyStatusCmd due to engine is null");
//                //TODO 返回值是否为空？
//                return "";
//            }
            //TODO 老的业务需求，目前接口没有实现，后续再看
//            if (MdmEngineProxy.getInstance().isIsOwnerMode()) {
//                payload.put(FIELD_DM_MODEL, VALUE_COPE);
//            } else {
//                payload.put(FIELD_DM_MODEL, VALUE_BYOD);
//            }

            List<RestrictionStatusEntity> entities = PolicyRepository.getInstance().getRestrictionStatus();
            for(RestrictionStatusEntity entity : entities) {
                Map<String, Object> object = new HashMap<>();
                object.put("expectedVal", entity.getExpected());
                object.put("actualVal", entity.getActual());
                restriction.put(entity.getName(), object);
            }

            body.put("policyStatus", restriction);
        } catch (Exception e) {
            CommonLogger.error("mdm policy error in device info ", e);
        }
        return new Gson().toJson(body);
    }


    public static class Result {
        public static final String CODE_ERROR = "ERROR";
        public static final String CODE_OK = "OK";
        private String code = CODE_OK;
        private String message;
        private String error;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getError() {
            return error;
        }

        public void setError(String error) {
            this.error = error;
        }
    }
}
